package cn.gzsendi.config.mybatis;

import cn.gzsendi.config.mybatis.enumn.DatabaseType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @Program: mybatis_test
 * @Description: 注解切面编程
 * @Author: tsh
 * @Create: 2021-01-08
 */
@Aspect
@Component
@Slf4j
public class DataSourceAspect {

    @Pointcut("@annotation(cn.gzsendi.config.mybatis.TargetDataSource)")
    public void dataSourcePointCut() {

    }

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();

        //todo 通过注解的方式去选择数据源
        TargetDataSource targetDataSource = method.getAnnotation(TargetDataSource.class);
        if (targetDataSource == null) {
            log.info("默认数据源 master");
            DynamicDataSource.setDataSource(DatabaseType.master.toString());
        } else {
            log.info("切换数据源： " + targetDataSource.name());
            DynamicDataSource.setDataSource(targetDataSource.name());
        }

        try {
            return point.proceed();
        } finally {
            //todo 选择完之后 清除当前数据源
            DynamicDataSource.clearDataSource();
        }
    }
}

